import os
import glob
import time
import concurrent.futures
import argparse
from PIL import Image
from PIL import ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True

def convert_to_jpg(image_file, outdir, width=960, height=540):
    try:
        img = Image.open(image_file)
        new_img = img.resize((width, height), Image.BICUBIC)
        # 获取相对路径，用于在输出目录中创建相同的子文件夹结构
        rel_path = os.path.relpath(image_file, args.input_dir)
        output_file = os.path.join(outdir, os.path.splitext(rel_path)[0] + '.jpg')
        os.makedirs(os.path.dirname(output_file), exist_ok=True)  # 确保输出目录存在
        new_img.save(output_file, 'JPEG', quality=95)
    except (IOError, OSError) as e:
        print(f"损坏的图片: {image_file}")

def process_images(thread_count, input_dir, output_dir, width, height):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    with concurrent.futures.ThreadPoolExecutor(max_workers=thread_count) as executor:
        # 递归遍历所有子文件夹
        for root, _, files in os.walk(input_dir):
            for file in files:
                if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                    image_file = os.path.join(root, file)
                    executor.submit(convert_to_jpg, image_file, output_dir, width, height)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Image Resize with Multithreading')
    parser.add_argument('--input-dir', type=str, default='./SN007_20240629', help='Input directory containing images')
    parser.add_argument('--output-dir', type=str, default='./SN007_20240629_960_540', help='Output directory for resized images')
    parser.add_argument('--width', type=int, default=960, help='Width of the resized images')
    parser.add_argument('--height', type=int, default=540, help='Height of the resized images')
    parser.add_argument('--threads', type=int, default=16, help='Number of threads for parallel processing')
    
    args = parser.parse_args()

    print("开始处理：")
    start = time.time()

    process_images(args.threads, args.input_dir, args.output_dir, args.width, args.height)

    end = time.time()
    print("处理完成，resize照片耗时: %s分" % ((end - start) / 60))